package com.ruoyi.hmy.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.context.AuthenticationContextHolder;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.hmy.service.IHmyAccountService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class HmyAccountServiceImpl implements IHmyAccountService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public String login(LoginBody loginBody) {
        // 用户验证
        Authentication authentication = null;
        if (Constants.USER_TYPE_MGR.equals(loginBody.getUsertype())) {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);

        } else if (Constants.USER_TYPE_SHOP.equals(userType)) {

            Shop shop = mongoRepository.findOne(Shop.class, Maps.newHashMap("name", userName, "password", password));
            if(shop==null){
                return Rets.failure("没有改账号");
            }
            if(shop.getDisabled() == 1){
                return Rets.failure("该商户已停用");
            }
            if (shop == null) {
                return Rets.failure("账号或密码错误");
            }
            token = JwtUtil.sign(shop);
        }
    }
}
